package com.bnz.cart.controller;

import com.bnz.cart.entity.group.Cart;
import com.bnz.cart.service.CartService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zfs
 * @since 2022-12-15
 */
@Controller
public class CartController {
    @Autowired
    private CartService cartService;
    //展示购物车列表
    @GetMapping({"/","/cart.html"})
    public String listCart(Model model, HttpSession session){
        //定义第三方登录地址
        String loginUrl = "http://auth.bnz.com/login.html?returnUrl=http://cart.bnz.com";
        //得到当前登录用户
        String name = (String) session.getAttribute("name");
        if(StringUtils.isNotBlank(name)){
            //获取购物车列表
            List<Cart> cartList = cartService.getCartList(name);
            //将购物车列表放到model中
            model.addAttribute("cartList",cartList);
        }else{  //如果未登录，就跳转到登录页面进行登录
            return "redirect:" + loginUrl;
        }
        return "cart";
    }

    /**
     * 2. 添加购物车
     * @param id sku商品id
     * @param num 商品数量
     * @return 添加完成后跳转到购物车列表中
     */
    @GetMapping("cart/add")
    public String addCart(Long id, int num, Model model, HttpSession session){
        //定义第三方登录地址
        String loginUrl = "http://auth.bnz.com/login.html?returnUrl=http://cart.bnz.com";
        //得到登录用户
        String name = (String) session.getAttribute("name");
        if(StringUtils.isNotBlank(name)){
            //添加商品到购物车列表中
            List<Cart> cartList = cartService.add(id,num,name);
            //将购物车列表添加到model中
            model.addAttribute("cartList",cartList);
            return "cart";
        }
        return "redirect:" + loginUrl;
    }
}
